var DBFactory = require('../db/mysql_db');
var mechanismDao = module.exports;
var request = require('request');
var config = require('../config');

mechanismDao.list = function(data, cb) {
    var sql = 'select * from mechanism where 1 ';
    var sql_total = 'select count(*) as count from mechanism where 1 ';
    var arr = [];
    if(data.id) {
        sql += ' and id = ? ';
        sql_total += ' and id = ? ';
        arr.push(data.id);
    }
    if(data.mechanism_name) {
        sql += ' and mechanism_name like ? ';
        sql_total += ' and mechanism_name like ? ';
        arr.push('%'+data.mechanism_name+'%');
    }
    DBFactory.executeSql(sql_total, arr, 'getMechanismListTotal', function(err, total) {
        if(err) return cb(err);
        DBFactory.executeSql(sql, arr, 'getMechanismListTotal', function(e, result) {
            if(e) return cb(e);
            sql += ' limit ?, ? ';
            arr.push(data.start);
            arr.push(data.size);
            cb(null, {total: total[0].count, data: result});
        })
    })
}

mechanismDao.save = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var mechanism = {};
    ['id', 'mechanism_name', 'mechanism_avatar', 'openid', 'telephone', 'province', 'city',
        'area', 'address', 'services', 'crowds', 'des', 'ext_info'].forEach(function(m) {
        if(data[m]) mechanism[m] = data[m];
    })
    var sql = 'replace into mechanism set ? ';
    DBFactory.executeSql(sql, mechanism, 'mechanismSave', function(err, result) {
        if(err) return cb(err);
        cb(null, {msg:'设置成功！', id: result.insertId});
    })
}

mechanismDao.auth = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'update mechanism set status = ? where id in( ? ) ';
    DBFactory.executeSql(sql, [data.status, data.ids], 'mechanismAuth', function(err, result) {
        if(err) return cb(err);
        cb(null, result);
    })
}

mechanismDao.checkId = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'select id from mechanism where openid = ? ';
    DBFactory.executeSql(sql, [data.openid], 'checkId', function(err, result) {
        if(err) return cb(err);
        if(result.length < 0 || parseInt(data.mechanism_id) != result[0].id) return cb('身份有误，请重试！');
        cb(null, data);
    })
}

function getAccessToken(cb) {
    var getAccessTokenUrl;
    getAccessTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + config.WX_AUTH.AppID +
        '&secret=' +  config.WX_AUTH.AppSecret ;
    request({url: getAccessTokenUrl, method: 'GET'}, function (error, response, body) {
        if(error || !body) {
            console.log(error);
            return cb('获取openid失败！');
        } else {
            try {
                var accessTokenInfo = JSON.parse(body);
                if(!accessTokenInfo.access_token) return cb('获取accessToken失败！');
                cb(null, accessTokenInfo);
            } catch (e) {
                console.log(e);
                return cb('获取getAccessToken失败！');
            }
        }
    });
}
mechanismDao.getQrCode = function(data, cb) {
    getAccessToken(function(err, accessToken) {
        if(err) return cb(err);
        var getQrUrl = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + accessToken.access_token;
        var options = {
            url : getQrUrl ,
            encoding: null,
            method : 'POST',
            body: JSON.stringify(data),
            headers : {
                'Content-Type': 'application/json; charset=UTF-8'
            }
        };
        request(options, function (error, rsp) {
            if(error){
                cb(error);
                return;
            }
            var qrCode = new Buffer(rsp.body).toString('base64');
            qrCode = encodeURI(qrCode);
            cb(null, qrCode);
        });
    })
}
mechanismDao.getMechanismInfo = function(data, cb) {
    if(!data) return cb(new ERR(500));
    var sql = 'select * from mechanism where openid = ? ';
    DBFactory.executeSql(sql, [data.openid], 'getMechanismInfo', function(err, result) {
        if(err) return cb(err);
        var mechanism = {};
        if(!result || (result[0] && result[0].status == 0)) {
            mechanism.data = result[0];
            getPurchaseInfo(mechanism, cb)
        } else {
            mechanism.data = result[0];
        }
    })
}
function getPurchaseInfo(mechanism, cb) {
    var sql = 'select * from purchase_item where id = 1 ';
    DBFactory.executeSql(sql, [], 'getPurchaseInfo', function(err, result) {
        if(err) return cb(err);
        mechanism.orderInfo = result[0];
        cb(null, mechanism);
    })
}
